import os

from flask import Flask

def create_app(test_conf=None):
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_mapping(
        SECRET_KEY='dev',
        JSON_AS_ASCII=False,
        SQLALCHEMY_DATABASE_URI='sqlite:///%s'%os.path.join(app.instance_path, 'app.sqlite')
    )
    if test_conf is None:
       app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_conf)
    # app.config
    # app.config.from_mapping()
    from flask_jsontools import DynamicJSONEncoder

    class ApiJsonEncoder(DynamicJSONEncoder):
        def default(self, o):
            import datetime
            app.logger.info(isinstance(o, datetime.datetime))
            if isinstance(o, datetime.datetime):
                return o.isoformat(' ')
            if isinstance(o, datetime.date):
                return o.isoformat()
            if isinstance(o, set):
                return list(o)

            return DynamicJSONEncoder.default(self, o)

    app.json_encoder = ApiJsonEncoder

    try:
        os.makedirs(app.instance_path)
    except IOError:
        ...

    from . import models
    models.init_app(app)

    # from .task import bp
    from .auth import bp
    app.register_blueprint(bp)

    # app.register_error_handler

    # from . import alipay_oauth
    return app
